using MediatR;
using Microsoft.EntityFrameworkCore;
using Medical.Domain;
using Medical.ErrorCode;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	public class GetRolesListQueryHandler : IRequestHandler<GetRolesListQuery, ApiPaging<RoleDto>>
	{
		private readonly IBaseRepository<Role> _repo;

		public GetRolesListQueryHandler(IBaseRepository<Role> repo)
		{
			_repo = repo;
		}

		public async Task<ApiPaging<RoleDto>> Handle(GetRolesListQuery request, CancellationToken cancellationToken)
		{
			var query = _repo.GetAll();
			if (!string.IsNullOrEmpty(request.NameKeyword)) query = query.Where(x => ((Role)x).Name.Contains(request.NameKeyword));
			if (request.IsActive.HasValue) query = query.Where(x => ((Role)x).IsActive == request.IsActive.Value);
			var totalCount = await query.CountAsync(cancellationToken);
			var items = await query.OrderByDescending(x => ((Role)x).CreatedAt).Skip((request.Page - 1) * request.Size).Take(request.Size)
				.Select(x => (Role)x).Select(r => new RoleDto { RoleId = r.RoleId, Name = r.Name, Description = r.Description, IsActive = r.IsActive, CreatedAt = r.CreatedAt, UpdatedAt = r.UpdatedAt })
				.ToListAsync(cancellationToken);
			var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);
			return new ApiPaging<RoleDto> { totalCount = totalCount, totalPage = totalPage, data = items };
		}
	}
}
